package com.example.learn01.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.learn01.common.Constants;
import com.example.learn01.common.Result;
import com.example.learn01.controller.dto.UserDTO;
import com.example.learn01.entity.User;
import com.example.learn01.exception.ServiceException;
import com.example.learn01.mapper.UserMapper;
import com.example.learn01.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.learn01.utils.TokenUtils;
import org.springframework.stereotype.Service;

import java.awt.geom.QuadCurve2D;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-04-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public Result login(UserDTO userDTO){
        QueryWrapper<User> queryWrapper=new  QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        // 数据查询
        User user;
        try {
            user=getOne(queryWrapper);
        }catch (Exception e){
        //  服务器错误
            throw  new ServiceException(Constants.COOE_500,"系统错误");
        }
        if(user!=null){
            //复制user的对象值到userDTO上
            BeanUtil.copyProperties(user,userDTO,true);
            String token= TokenUtils.genToken(user.getId().toString(),user.getPassword());
            userDTO.setToken(token);
            Result res=new Result();
            return res.success("success",userDTO);
        }else {
            //  数据错误
             throw  new ServiceException(Constants.COOE_200,"用户或密码错误");
        }

   }

}
